package org.peacewing.facade;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.javaforever.gatescore.action.CompileAction;
import org.peacewing.compiler.SGSCompiler;
import org.peacewing.domain.Project;
import org.peacewing.domain.ValidateInfo;
import org.peacewing.exception.ValidateException;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class GenerateSampleCodeController
 */

public class GenerateSampleCodeFacade extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GenerateSampleCodeFacade() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		Map<String, Object> result = new TreeMap<String, Object>();
		try {

			String sourcefolder = request.getSession().getServletContext().getRealPath("/") + "source/";
			sourcefolder = sourcefolder.replace('\\', '/');

			String sgscode = request.getParameter("code");
			System.out.println(sgscode);
			String ignoreWarning = request.getParameter("ignoreWarning");
			boolean ignoreWarningBoolean = ignoreWarning == null || ignoreWarning.equals("")?false:Boolean.parseBoolean(ignoreWarning);
			Project project = SGSCompiler.translate(sgscode,ignoreWarningBoolean);

			System.out.println(sourcefolder);
			project.setFolderPath(sourcefolder);
			if (project.getTechnicalstack() == null || "".equalsIgnoreCase(project.getTechnicalstack())
					|| "smeu".equalsIgnoreCase(project.getTechnicalstack())) {
				String rootPath = (request.getSession().getServletContext().getRealPath("/")).replace('\\', '/');
				String templatesPath = rootPath+"templates/";
				String savePath = rootPath + "source/";
				project.setSourceFolderPath(templatesPath);
				project.generateProjectZip();
				
				String frontProjectName = CompileAction.compile(sgscode,templatesPath,savePath,true,ignoreWarningBoolean);

				result.put("success", true);
				result.put("projectName", project.getStandardName());
				result.put("frontProjectName", frontProjectName);
				
				out.print(JSONObject.fromObject(result));
			}
		} catch (ValidateException ev) {
			result.put("success", false);
			ValidateInfo info = ev.getValidateInfo();
			List<String> compileErrors = info.getCompileErrors();
			result.put("compileErrors", compileErrors);
			List<String> compileWarnings = info.getCompileWarnings();
			result.put("compileWarnings", compileWarnings);
			out.print(JSONObject.fromObject(result));
		} catch (Exception e) {
			if (!(e instanceof ValidateException)) {
				e.printStackTrace();
				result.put("success", false);
				if (e.getMessage() != null && !e.getMessage().equals("")) {
					result.put("reason", e.getMessage());
				} else {
					result.put("reason", "空指针或其他语法错误！");
				}
				out.print(JSONObject.fromObject(result));
			}
		} finally {
			out.close();
		}
	}
}
